package com.liuch.mybatis.parsing;

import cn.hutool.core.util.StrUtil;
import lombok.Data;

/**
 * SQL解析器
 */
@Data
public class GenericTokenParser {
    private String startToken; // eg: #{
    private String endToken; //eg: }
    private TokenHandler tokenHandler;

    public GenericTokenParser(String startToken, String endToken, TokenHandler tokenHandler) {
        this.startToken = startToken;
        this.endToken = endToken;
        this.tokenHandler = tokenHandler;
    }

    public String parse(String text){
        if(StrUtil.isBlank(text)){
            return "";
        }

        StringBuilder result = new StringBuilder();
        int offset = 0;
        int start = text.indexOf(this.startToken);
        while(start > -1){
            int end = text.indexOf(this.endToken, start);
            if(end == -1){
                result.append(text.substring(offset));
                offset = text.length();
            }else{
                result.append(text.substring(offset, start));
                offset = start + this.startToken.length();
                String paramName = text.substring(offset, end);
                System.out.println(paramName);
                //把问号抽取出来改成可以自己指定
                result.append(this.tokenHandler.handleToken(paramName));
                offset = end + this.endToken.length();
            }
            start = text.indexOf(this.startToken, offset);
        }
        if(offset < text.length()){
            result.append(text.substring(offset));
        }
        return result.toString();
    }

    public static void main(String[] args) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String sql = genericTokenParser.parse("select * from user where id = #{id} and name = #{name}");
        System.out.println(sql);

        System.out.println(parameterMappingTokenHandler.getParameterMappings());

    }

}
